Skip to main content

Financial data analysis II python preview -- crawling a province's university rankings with bs4

· 1 Minutes to read
Allen Ma

Case (I) python warm-up

Project 3: Crawling the university ranking of a province

Enter the name of a province and crawl the data from "SoftTech China's Best Universities Ranking 2020" (http://www.zuihaodaxue.cn/zuihaodaxuepaiming2020.html) developed by Shanghai Jiao Tong University to output the province's 2020 University rankings for that province in 2020. Input: Guangdong Output.在这里插入图片描述

import requests
from bs4 import BeautifulSoup
import bs4


def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""


def fillUnivList(ulist, html):
soup = BeautifulSoup(html, "html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag):
tds = tr('td')
ulist.append([tds[0].string, tds[1].string, tds[2].string])


def printUnivList(ulist, num, place):
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print("{:^10}\t{:^6}\t{:^10}".format("排名", "学校名称", "省市"))
for i in range(num):
u = ulist[i]
if u[2] == place:
print(tplt.format(u[0], u[1], u[2], chr(12288)))
# print("{:^10}\t{:^6}\t{:^10}".format(u[0], u[1], u[2]))
else:
continue

def main():
uinfo = []
url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 549, "广东") # 20 univs


main()

Results of the run. 在这里插入图片描述